package com.lazyfish.scss.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class EncodingFilter implements Filter {

    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        //System.out.println("我已执行过滤。");
         //设置编码格式为 UTF-8
        if(request.getServletPath().contains("html")){
        	request.setCharacterEncoding("UTF-8");
        	response.setContentType("text/html; charset=UTF-8");
        }else{
    		request.setCharacterEncoding("UTF-8");
    		response.setContentType("text/json; charset=UTF-8");
        }

        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        chain.doFilter(request, response);
    }

    public void init(FilterConfig config) {
        System.out.println("过滤器init()执行了~");
    }

}